package app.fugema.shop.main.order.view;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.collection.SparseArrayCompat;
import androidx.lifecycle.Observer;
import app.fugema.shop.main.goods.view.GoodsDetailActivity;
import app.fugema.shop.main.order.adapter.ShoppingCartAdapter;
import app.fugema.shop.main.order.model.ShopCartProduct;
import app.fugema.shop.main.order.model.ShopModifyCountResult;
import app.fugema.shop.main.order.model.ShoppingCountBean;
import app.fugema.shop.main.order.model.ShoppingSubmitInfo;
import app.fugema.shop.main.wallet.model.BuyBean;
import app.fugema.shop.main.wallet.view.WalletPayDialogFragment;

import com.base.common.app.LoginUtils;
import com.base.common.netBeanPackage.BaseApiResult;
import com.base.common.netBeanPackage.LiveDataWrapper;
import com.base.common.utils.DialogUtils;
import com.base.common.utils.OnClickCheckedUtil;
import com.base.common.utils.UIUtils;
import com.base.common.view.adapter.ada.BaseRVAdapter;
import com.base.common.view.base.BaseTitleActivity;
import com.base.common.view.base.OnGetDataListener;
import com.base.common.view.widget.statelayout.StateLayout;
import com.base.common.viewmodel.BaseViewObserver;
import com.jeremyliao.liveeventbus.LiveEventBus;
import app.fugema.shop.R;
import app.fugema.shop.constants.AppConstants;

import app.fugema.shop.databinding.ShoppingCartActivityBinding;

import app.fugema.shop.main.order.vm.ShoppingCartVM;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class ShoppingCartActivity extends BaseTitleActivity<ShoppingCartActivityBinding, ShoppingCartVM> implements OnGetDataListener
{
    private String userKey;
    public static void start(Context context)
    {
        if (!LoginUtils.isLogin())
        {
            UIUtils.showToastSafes("未登录请登录");
            LoginUtils.loginIn();
            return;
        }
        context.startActivity(new Intent(context, ShoppingCartActivity.class));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shopping_cart_activity);
    }

    @Override
    protected void initNotificationReceipt()
    {
        super.initNotificationReceipt();
        LiveEventBus.get(AppConstants.EventKey.ORDER_CONFIRM_SUCCESS, BuyBean.class).observe(this, new Observer<BuyBean>() {
            @Override
            public void onChanged(BuyBean buyBean)
            {
                ShoppingCartActivity.this.buyBean = buyBean;
                isShowPayDialog = true;
                initData(getIntent());
            }
        });
    }

    private SparseArrayCompat<Boolean> sparseArraySelect = new SparseArrayCompat<>();//保存当前选中的商品的状态

    private ShoppingCartAdapter cartAdapter;

    private boolean isShowPayDialog = false;//是否显示支付弹窗
    private BuyBean buyBean;

    private boolean isEdit = false;//是否是编辑模式

    @Override
    protected void onResume()
    {
        super.onResume();
        if (isShowPayDialog)
        {
            isShowPayDialog = false;
            if (buyBean != null)
            {
                addFragment(WalletPayDialogFragment.newInstance(buyBean));
            }
        }
    }
    @Override
    protected int getStatusBarColor()
    {
        return R.color.redColor;
    }
    @Override
    protected void initView()
    {
        super.initView();
        setCloseImg(R.mipmap.ic_back_white);
        setTitle("购物车",R.color.white);
        setRightText("管理",R.color.white);

        setRightTextOnClick(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view)
            {
                buttonTextChanged();
            }
        });
        binding.rbRadio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                boolean isChecked = !v.isSelected();
                checkedChanged(isChecked);
            }
        });

        binding.rbRadioText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.rbRadio.callOnClick();
            }
        });


        cartAdapter = new ShoppingCartAdapter() {
            @Override
            public void onItemClick(View view, BaseRVAdapter adapter, int onclickType, int position, ShopCartProduct bean)
            {
                super.onItemClick(view, adapter, onclickType, position, bean);
                switch (view.getId()) {
                    case R.id.rclItemView:
                    case R.id.rbRadio:
                        boolean bb = !bean.getSelected();
                        setSelectPosition(position, bb);
                        sparseArraySelect.put(Integer.parseInt(bean.getId()), bb);
                        changePriceSum();
                        break;
                    case R.id.ivGoodsAdd:
                        UIUtils.showToastSafes("加一");
                        ShoppingCountBean skus = new ShoppingCountBean();
                        List<ShoppingCountBean.SkuCountBean> skuIdCount = new ArrayList<>();
                        int addCount = Integer.parseInt(bean.getCount()) + 1;
                        skuIdCount.add( new ShoppingCountBean.SkuCountBean(bean.getSkuId(), String.valueOf( addCount )));
                        skus.setSkus(skuIdCount);
                        modofyShoppingCart( skus );
                        break;
                    case R.id.ivGoodsReduce:
                        UIUtils.showToastSafes("减一");

                        if (Integer.parseInt(bean.getCount()) > 1)
                        {
                            ShoppingCountBean skus2 = new ShoppingCountBean();
                            List<ShoppingCountBean.SkuCountBean> skuIdCount2 = new ArrayList<>();
                            int reCount = Integer.parseInt(bean.getCount()) - 1;
                            skuIdCount2.add( new ShoppingCountBean.SkuCountBean(bean.getSkuId(), String.valueOf( reCount )));
                            skus2.setSkus(skuIdCount2);
                            modofyShoppingCart( skus2 );
                        } else {
                            DialogUtils.showSimpleDialog(getActivity(), false, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    deleteGoods(bean);
                                }
                            }, "您确认要删除该商品吗？");
                        }

                        break;
                    case R.id.rtvSpec:
                        /*
                        viewModel.getSkuList(bean).observe(getActivity(), new BaseViewObserver<LiveDataWrapper<GoodsDetailBean>>(getActivity()) {
                            @Override
                            protected void onSuccess(LiveDataWrapper<GoodsDetailBean> data) {
                                //data.data.getData()
                                ShoppingSpecificationDialog specificationDialog = ShoppingSpecificationDialog.getInstance(null, true);
                                specificationDialog.setOnResultShoppingCartSku(new ShoppingSpecificationDialog.OnResultShoppingCartSku() {
                                    @Override
                                    public void onResultCartSku(ShopCartProduct.ShopCartItemsBean dataBean) {
                                        if (dataBean.getSkuId() != bean.getSkuId()) {
                                            shopCartChangeSku(bean, dataBean.getSkuId());
                                        }
                                    }
                                });
                                addFragment(specificationDialog);
                            }

                            @Override
                            public boolean isEmptyData(LiveDataWrapper<GoodsDetailBean> data) {
                                return UIUtils.isEmpty(data.data.getData());
                            }
                        });
                        */
                        break;

                    case R.id.givGoodsImage:
                        GoodsDetailActivity.start(getActivity(), Integer.parseInt( bean.getId() ));
                        break;
                }
            }
        };


        binding.rvRecyclerView.setAdapter(cartAdapter);

        binding.rtvOK.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {

                if (isEdit)
                {
                    deleteGoods();
                    return;
                }


                if (cartAdapter != null && cartAdapter.getItemCount() > 0)
                {
                    if (cartAdapter.getSelectPosition() == -1) {
                        UIUtils.showToastSafesClose("请选择需要结算的商品");
                        return;
                    }
                    List<ShopCartProduct> list = new ArrayList<>();
                    StringBuffer itemIdStr = new StringBuffer();
                    //获取勾选的商品 itemId
                    for (int i = 0; i < cartAdapter.getItemCount(); i++)
                    {
                        if (cartAdapter.getItemBean(i) instanceof ShopCartProduct)
                        {
                            ShopCartProduct cartItemsBean = (ShopCartProduct) cartAdapter.getItemBean(i);
                            if (cartItemsBean.getSelected())
                            {
                                list.add(cartItemsBean);
                                if(UIUtils.isNotEmpty( itemIdStr.toString() ))
                                {
                                    itemIdStr.append(",");
                                }
                                itemIdStr.append(cartItemsBean.getCartItemId());
                            }
                        }
                    }

                    ShoppingSubmitInfo cartInfo = new ShoppingSubmitInfo();
                    cartInfo.setBuyNow(false);
                    cartInfo.setIdStr(itemIdStr.toString());
                    // 去结算
                    ShoppingConfirmOrderActivity.start(getActivity(), cartInfo);
                }
            }
        });
        viewUtils.setRefreshStateLayout(binding.rvRecyclerView, this, this, false);
        viewUtils.getStateLayout().setTipText(StateLayout.EMPTY, "您的购物车空空如也！");

        userKey = LoginUtils.getToken();

    }


    private void buttonTextChanged()
    {
        if (isEdit)
        {
            isEdit = false;
            setRightText("管理",R.color.white);
            binding.rtvOK.setText("结算");
        }
        else
        {
            setRightText("完成",R.color.white);
            isEdit = true;
            binding.rtvOK.setText("删除");
            checkedChanged(false);
        }
    }

    private void checkedChanged(boolean isChecked)
    {
        if (cartAdapter != null && cartAdapter.getItemCount() > 0)
        {
            for (int i = 0; i < cartAdapter.getItemCount(); i++)
            {
                if (cartAdapter.getItemBean(i) instanceof ShopCartProduct)
                {
                    ShopCartProduct cartItemsBean = (ShopCartProduct) cartAdapter.getItemBean(i);
                    cartItemsBean.setSelected(isChecked);
                    sparseArraySelect.put(Integer.parseInt( cartItemsBean.getId() ), isChecked);
                }
            }
            changePriceSum();
        }
    }

    @Override
    protected void initData(Intent intent)
    {
        super.initData(intent);
        onGetData(1);
    }

    private void changePriceSum()
    {
        BigDecimal sum = BigDecimal.ZERO;
        boolean bb = true;
        if (cartAdapter.getItemCount() == 0) bb = false;
        for (int i = 0; i < cartAdapter.getItemCount(); i++)
        {
            if (cartAdapter.getItemBean(i) instanceof ShopCartProduct)
            {
                ShopCartProduct cartItemsBean = (ShopCartProduct) cartAdapter.getItemBean(i);
                if (cartItemsBean.getSelected())
                {

                    sum = sum.add(new BigDecimal(cartItemsBean.getPrice()));
                }
                else
                {
                    bb = false;
                }
            }
        }
        binding.rbRadio.setSelected(bb);
        binding.tvPriceSum.setText("¥" + sum.setScale(2).stripTrailingZeros().toPlainString());
    }

    @Override
    public void onGetData(int pn)
    {

        viewModel.queryCartProduct(userKey)
                 .observe(this, new BaseViewObserver<LiveDataWrapper<List<ShopCartProduct>>>(viewUtils.getStateLayout())
                 {
                     @Override
                     protected void onSuccess(LiveDataWrapper<List<ShopCartProduct>> data)
                     {
                         for (ShopCartProduct cartItemsBean : data.data)
                         {
                             cartItemsBean.setSelected(sparseArraySelect.get(Integer.parseInt(cartItemsBean.getId()), false));
                         }
                         viewUtils.setDataListRefreshLayout(cartAdapter, 1, 20, data.data);

                         changePriceSum();
                     }

                     @Override
                     public boolean isRefreshLayoutData()
                     {
                         return true;
                     }

                     @Override
                     public boolean isEmptyData(LiveDataWrapper<List<ShopCartProduct>> data)
                     {
                         return UIUtils.isEmpty(data.data);
                     }

                     @Override
                     protected void onEmptyLayout()
                     {
                         super.onEmptyLayout();
                         cartAdapter.clear();
                         binding.rbRadio.setSelected(false);
                         binding.tvPriceSum.setText("¥0.00");
                     }
                 });

    }

    private void deleteGoods()
    {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < cartAdapter.getItemCount(); i++)
        {
            if (cartAdapter.getItemBean(i) instanceof ShopCartProduct)
            {
                ShopCartProduct itemsBean = (ShopCartProduct) cartAdapter.getItemBean(i);
                if (itemsBean.getSelected())
                {
                    list.add(itemsBean.getSkuId() );
                }
            }
        }
        if (UIUtils.isEmpty(list))
        {
            UIUtils.showToastSafes("请选择要删除的商品");
        }
        else
        {
            buttonTextChanged();

            viewModel.deleteCartBySkuIds(list , userKey).observe(this, new BaseViewObserver<LiveDataWrapper<BaseApiResult>>(getActivity()) {
                @Override
                protected void onSuccess(LiveDataWrapper<BaseApiResult> data) {
                    initData(getIntent());
                    UIUtils.showToastSafes("商品已从购物车删除");
                }
            });
        }

    }

    private void deleteGoods(ShopCartProduct bean)
    {

        viewModel.deleteCartProduct(bean.getSkuId(),userKey).observe(getActivity(), new BaseViewObserver<LiveDataWrapper<BaseApiResult>>(getActivity()) {
            @Override
            protected void onSuccess(LiveDataWrapper<BaseApiResult> data)
            {
                for (int i = 0; i < cartAdapter.getItemCount(); i++)
                {
                    if (cartAdapter.getItemBean(i) instanceof ShopCartProduct)
                    {
                        ShopCartProduct itemsBean = (ShopCartProduct) cartAdapter.getItemBean(i);
                        if (itemsBean.getSkuId() == bean.getSkuId())
                        {
                            cartAdapter.remove(i);
                            break;
                        }
                    }
                }
                UIUtils.showToastSafes("商品已从购物车删除");
            }
        });

    }

    //修改购物车的 数量  等信息
    private void modofyShoppingCart(ShoppingCountBean skusCount)
    {
        viewModel.updateCartChange(skusCount,userKey).observe(this, new BaseViewObserver<LiveDataWrapper<ShopModifyCountResult>>(getActivity())
        {
            @Override
            protected void onSuccess(LiveDataWrapper<ShopModifyCountResult> data)
            {
                if( data.data.isSuccess() )
                {
                    changePriceSum();
                }
            }
        });
    }

    //修改购物车 规格等信息
    private void shopCartChangeSku(ShopCartProduct bean, int skuId)
    {
        /*
        viewModel.shopCartChangeSku(bean.getBasketId(), bean.getShopId(), bean.getProdId(), skuId).observe(this, new BaseViewObserver<LiveDataWrapper<BaseResponse>>(getActivity()) {
            @Override
            protected void onSuccess(LiveDataWrapper<BaseResponse> data) {
                initData(getIntent());
            }
        });
        */
    }


}
